package com.kzn.controller;


import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kzn.entity.Admin;
import com.kzn.service.IAdminService;
import com.kzn.service.impl.AdminServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author sorclown
 * @since 2022-02-05
 */
@RestController
@RequestMapping("/api/admin")
public class AdminController {

    private IAdminService adminService;

    public AdminController() {
        super();
    }

    @Autowired
    public AdminController(IAdminService adminService) {
        this.adminService = adminService;
    }



    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public boolean register(@RequestBody Admin admin) {
        if (null != admin) {
            return adminService.save(admin);
        } else {
            return false;
        }
    }

    @RequestMapping(value = "/logOut", method = RequestMethod.GET)
    public boolean logOut(@RequestParam Integer adminId) {
        if (null != adminId) {
            QueryWrapper<Admin> adminQueryWrapper = new QueryWrapper<>();
            adminQueryWrapper.eq("id",adminId);
            return adminService.remove(adminQueryWrapper);
        } else {
            return false;
        }
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public boolean updateAdmin(@RequestBody Admin admin) {
        if (null != admin.getId()) {
            return adminService.updateById(admin);
        } else {
            return false;
        }
    }

    @RequestMapping(value = "/selectById", method = RequestMethod.GET)
    public String selectById(@RequestParam Integer adminId) {

        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.eq("id", adminId);
        Admin admin = adminService.getOne(wrapper);
        if (null != admin) {
            return JSONUtil.parse(admin).toString();
        } else {
            return null;
        }
    }


    @RequestMapping(value = "/logIn", method = RequestMethod.GET)
    public String logIn(@RequestParam String phone, @RequestParam String password) {
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", phone);
        Admin admin = adminService.getOne(wrapper);
        if (admin != null && phone.equals(admin.getPhone()) && password.equals(admin.getPassword())){
            return JSONUtil.parse(admin).toString();
        }else {
            return null;
        }
    }
}
